<script setup lang="ts">
import { computed } from 'vue'
import { Todo } from '../App.vue'
interface Props {
  list: Todo[]
}
// 保存 props 在 script 中使用
const props = defineProps<Props>()
// 定义 emit
const emit = defineEmits(['changeDone', 'delTodo', 'checkAll'])
const changeFn = (id: number) => {
  // 触发父组件的自定义事件并传值
  emit('changeDone', id)
}

const delFn = (id: number) => {
  emit('delTodo', id)
}

// 计算全选状态 - ✨升级成带set的计算属性，提高代码可阅读性
const isCheckAll = computed({
  get() {
    return props.list.length > 0 && props.list.every((item) => item.done)
  },
  set(val: boolean) {
    // 子传父
    emit('checkAll', val)
  },
})
</script>

<template>
  <section class="main">
    <input
      id="toggle-all"
      class="toggle-all"
      type="checkbox"
      v-model="isCheckAll"
    />
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <li
        v-for="item in list"
        :key="item.id"
        :class="item.done ? 'completed' : ''"
      >
        <div class="view">
          <input
            class="toggle"
            type="checkbox"
            :checked="item.done"
            @change="changeFn(item.id)"
          />
          <label>{{ item.content }}</label>
          <button class="destroy" @click="delFn(item.id)"></button>
        </div>
        <input class="edit" value="Create a TodoMVC template" />
      </li>
    </ul>
  </section>
</template>
